<?php

namespace Frieza\Modules\Position\Controllers;

use Doraemon\pockets\constInterface\LinkConf;

use Doraemon\service\position\apiModule\HomeRecommendCard;
use Doraemon\tools\BlockType;
use Doraemon\tools\BlockTypeMapping;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;


class HouseCardController extends BaseController
{
    use BaseTrait;

    public $base_field_ext_type = HomeRecommendCard::EXT_TYPE_KA;

    const ALLOW_LINK = [
        LinkConf::LINK_ARTICLE,
        LinkConf::LINK_APP_ARTICLE_DETAIL,
    ];

    public function saveModule(Request $request, $baseInfoId)
    {
        $pos = $request->input('base.pos', 0);
        if ($pos <= 0) {
            throw new \Exception('展示位置必选大于0');
        }

        if ($pos > 20) {
            throw new \Exception('展示位置必须小于20');
        }

        $ext_type = $request->input('base.ext_type', 0);

        if (in_array($pos, [1, 3, 6, 9])) {
            if ($ext_type != HomeRecommendCard::EXT_TYPE_KA) {
                throw new \Exception('1、3、6、9必须为原生内容');
            }
        } else {
            if ($ext_type == HomeRecommendCard::EXT_TYPE_KA) {
                throw new \Exception('1、3、6、9才可以使用原生内容');
            }
        }
    }

    public function extendList(Grid $grid)
    {
        $grid->column('pos', '展示位置')->display(function ($title, Grid\Column $column) {
            $pos = $this->pos % 4;
            $map = ['primary','warning','success','info','danger'];
            return $column->label($map[$pos]);
        });
        $grid->column('card_info', '卡片信息')->display(function ($title, Grid\Column $column) {
            $display = [HomeRecommendCard::EXT_MAP[$this->ext_type] ?? ''];
            if ($this->ext_type == HomeRecommendCard::EXT_TYPE_KA) {
                $display[] = "内容类型:" . BlockType::name($this->obj_type);
                $display[] = "内容id:" . $this->obj_id;
            } else {
                $images[] = "<img src='{$this->pic_url}' style=\"max-width:200px;max-height:200px\" class=\"img img-thumbnail\"/>";
                $display[] = implode('<br/><br/>', $images);
            }

            return implode('<br/>', $display);
        });
        $grid->column('client_uid', '设计师账号uid');
    }

    public function extendSaveBaseInfo(Request $request): array
    {
        $ext_type = $request->input("base.ext_type", "");
        $link = [];
        switch ($ext_type) {
            case HomeRecommendCard::EXT_TYPE_FLOW:
                $single_pic_id = $request->input("single_pic_id", "");
                $pic_id = json_encode(compact('single_pic_id'));
                //链接处理
                $imgLink = $request->input("base.link", []);
                $link_type = $imgLink['link_type'] ?? '';
                $link_params = isset($imgLink['link_params']) ? json_encode($imgLink['link_params'], JSON_UNESCAPED_UNICODE) : '';
                $link = compact('link_type', 'link_params');
                break;
            case HomeRecommendCard::EXT_TYPE_KA:
                $obj = $request->input("obj", []);
                $link_type = $obj['link_type'] ?? '';
                $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'], JSON_UNESCAPED_UNICODE) : '';
                $link = compact('link_type', 'link_params');
                $objRs = BlockTypeMapping::getObjFromLinkParams($link_type, $link_params);
                $obj_id = $objRs['obj_id'] ?? null;
                $obj_type = $objRs['obj_type'] ?? null;
                $pic_id = json_encode(compact('obj_id', 'obj_type'));
                if (!in_array($link_type, self::ALLOW_LINK)) {
                    throw new \Exception('KA广告只支持整屋案例');
                }
                break;
            default:
                $pic_id = '';
                break;
        }

        return ['pic_id' => $pic_id, 'ext_type' => $ext_type] + $link;
    }

    public function beforeTitleForm(Form $form)
    {
        $help = [
            "卡片1优先广告售卖使用；",
            "3、6、9为设计师KA广告资源位；",
        ];
        $form->number('base.pos', '展示位置')->placeholder('位置')->required()->help("<span style='color: red'>" . implode('<br/>', $help) . "</span>");
    }

    public function beforeLinkForm(Form $form)
    {
        $form->radio('base.ext_type', '卡片类型')->options([
                HomeRecommendCard::EXT_TYPE_FLOW => 'Banner',
                HomeRecommendCard::EXT_TYPE_KA => '原生内容(无广告词)',
            ])
            ->when(HomeRecommendCard::EXT_TYPE_FLOW,  function (Form $form) {
                    $form->imgUpload('single_pic_id', 'Banner', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
                    $form->multiLinkSelect('base.link', '跳转链接');
            })->when(HomeRecommendCard::EXT_TYPE_KA, function (Form $form) {
                $form->multiLinkSelect('obj', '内容', self::ALLOW_LINK)->help('支持整屋案例');
            });
    }
}

